<?php

namespace app\admin\model;

class Usermodel extends Commonmodel {
    protected $roleTable = 'zhjs_role';
    protected $croomTable = 'zhjs_classroom';

    public function __construct(array $data = [])
    {
        $this->table = 'zhjs_user';
        $this->pk = 'id';
        parent::__construct($data);
    }

    public function findAllUserInfo($where = null, $isClass = false){
        $whereData = [
            ['u.is_delete', '=', 1],
            ['r.is_delete', '=', 1]
        ];

        if($isClass){
            $whereData[] = ['u.admintype', '=', 3];
            $whereData[] = ['c.is_delete', '=', 1];
        }else{
            $whereData[] = ['u.admintype', 'in', '1, 2'];
        }

        if($where)  $whereData = array_merge($where, $whereData);

        $userList = self::db()
            ->alias('u')
            ->field('u.id, u.username, u.create_date, u.status, u.mobile, r.name, c.name as croomname, c.status as cstatus')
            ->leftJoin([$this->roleTable=>'r'], 'u.rid=r.id')
            ->leftJoin([$this->croomTable=>'c'], 'u.cid=c.id')
            ->where($whereData)
            ->select()->toArray();

        return $userList;
    }

    /**
     * 保存
     * @param $data
     * @param null $id
     * @return bool|string
     */
    public function saveInfo($data, $id = null){

        if(!$data)  return false;

        if(!$id){
            $data['password'] = md5(md5($data['password']));
            $data['create_date'] = date("Y-m-d H:i:s", time());
        }

        if($id && $data['password'])  $data['password'] = md5(md5($data['password']));
        if($id && !$data['password'])  unset($data['password']);

        $res = parent::saveDataInfo($data, $id);

        if(!$res)  return false;
        return $res;
    }

    /**
     * 判断用户名是否重复
     * @param $username
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfoByName($username, $id = null){
        if($id)  return self::db()->field('id')->where([[['username', '=', $username], ['id', '<>', $id]]])->find();
        return self::db()->field('id')->where(['username'=>$username])->find();
    }
}

?>